package com.hrzyit.whistle.cases.ui.fragment

import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.hrzyit.base.common.BaseConstant
import com.hrzyit.base.ext.onClick
import com.hrzyit.base.ui.fragment.BaseMvpFragment
import com.hrzyit.base.utils.AppPrefsUtils
import com.hrzyit.whistle.cases.R
import com.hrzyit.whistle.cases.common.CaseConstant
import com.hrzyit.whistle.cases.data.bean.CaseIndexDeptInfoVo
import com.hrzyit.whistle.cases.data.bean.CaseIndexUserInfoVo
import com.hrzyit.whistle.cases.event.WhistleSelectInfoEvent
import com.hrzyit.whistle.cases.injection.component.DaggerCaseCenterComponent
import com.hrzyit.whistle.cases.injection.module.CaseCenterModule
import com.hrzyit.whistle.cases.presenter.WhistleSelectUserPresenter
import com.hrzyit.whistle.cases.presenter.view.WhistleSelectUserView
import com.hrzyit.whistle.cases.ui.adapter.IndexUserSelectAdapter
import kotlinx.android.synthetic.main.fragment_select_user_whistle.*
import me.yokeyword.indexablerv.IndexableLayout
import org.greenrobot.eventbus.EventBus

/**
 * 案件管理-吹哨人员选择界面 Fragment
 * @author YangWei
 * @date 2019/4/19
 */
class IndexUserWhistleFragment : BaseMvpFragment<WhistleSelectUserPresenter>(), WhistleSelectUserView {

    private lateinit var activity: Activity

    // 批转案件id
    private var caseId: Long? = null
    // 当前操作人id
    private var userId: Long? = null
    // 当前选择的单位id
    private var toDeptId: Long? = null
    // 当前选择的单位名称(简称)
    private var deptName: String? = null
    // 当前已选择的单位人员信息
    private var caseIndexDeptInfoVo: CaseIndexDeptInfoVo? = null

    private lateinit var indexAdapter: IndexUserSelectAdapter

    override fun onAttach(context: Context?) {
        super.onAttach(context)
        activity = context as Activity

    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        super.onCreateView(inflater, container, savedInstanceState)
        return inflater.inflate(R.layout.fragment_select_user_whistle, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        initAdapter()

        initData()

    }


    /**
     * 初始化数据
     */
    private fun initAdapter() {
        // 初始化数据
        // 适配器
        val indexLayout = mSelectUserWhistleIndexLayout as IndexableLayout
        indexLayout.setLayoutManager(LinearLayoutManager(activity))

        // setAdapter
        indexAdapter = IndexUserSelectAdapter(activity)
        indexLayout.setAdapter(indexAdapter)

        // set Material Design OverlayView
        indexLayout.setOverlayStyle_MaterialDesign(Color.BLUE)

        // 全字母排序。  排序规则设置为：每个字母都会进行比较排序；速度较慢
        indexLayout.setCompareMode(IndexableLayout.MODE_FAST)

        // 注册人员选项栏目点击事件
        indexAdapter.setOnItemContentClickListener { _, _, _, entity ->
            // 弹出批转窗口 CaseTransferConfirmPopup
            // 取消其它人员列表选中状态
            indexAdapter.items.forEach {
                if (entity.id == it.id) {
                    // 反选选择
                    it.isChecked = !entity.isChecked
                }
            }
            indexAdapter.notifyDataSetChanged()
        }

        // 重写 mSelectUserTransferHeaderBar 的 back 按钮事件,
        // 返回上一页，将选择中的人员信息反馈到吹哨单位选择界面
        mSelectUserWhistleHeaderBar.getLeftView().onClick {
            // 获取选中的项
            val checkedEntityList = indexAdapter.items.filter {
                it.isChecked
            }
            checkedEntityList.let {
                val whistleSelectInfoEvent = WhistleSelectInfoEvent()
                whistleSelectInfoEvent.toDeptId = this.toDeptId!!
                checkedEntityList.forEach {
                    it.deptName = this.deptName!!
                    it.deptId = this.toDeptId!!
                    whistleSelectInfoEvent.caseIndexUserInfoVoList.add(it)
                }
//                val transferCaseToDeptVo = TransferCaseToDeptVo()
//                // 批转的案件
//                transferCaseToDeptVo.caseId = this.caseId!!
//                // 批转到单位
//                transferCaseToDeptVo.toDeptId = this.toDeptId!!
//                transferCaseToDeptVo.deptName = this.deptName!!
//                // 批转到人员
////                transferCaseToDeptVo.userName = checkedEntity.name
////                transferCaseToDeptVo.toUserId = checkedEntity.id
//                // 当前操作人
//                transferCaseToDeptVo.userId = this.userId!!

                EventBus.getDefault().post(whistleSelectInfoEvent)

            }
            // 使用 EventBus 选中人员信息返回到吹哨单位选择界面
//            fragmentManager!!.popBackStack()
            val transaction = fragmentManager!!.beginTransaction()
            // 显示吹哨单位选择界面
            val indexDeptWhistleFragment =
                fragmentManager!!.findFragmentByTag(CaseConstant.TAG_FRAGMENT_DEPT_INDEX_FOR_WHISTLE)
            transaction.show(indexDeptWhistleFragment)
            transaction.commit()
            fragmentManager!!.popBackStack()
        }

    }


    /**
     * 加载数据
     */
    private fun initData() {

        caseIndexDeptInfoVo = arguments?.getSerializable("selectedDeptUser") as CaseIndexDeptInfoVo

        // 批转到单位id
        toDeptId = arguments?.getLong("toDeptId") // activity.intent.getLongExtra("toDeptId", 0L)

        // 批转到单位名称
        deptName = arguments?.getString("toDeptName")  // activity.intent.getStringExtra("toDeptName")

        // 当前操作人id
        userId = AppPrefsUtils.getLong(BaseConstant.KEY_SP_USER_TOKEN)

        // 案件id
        caseId = arguments?.getLong("caseId") // activity.intent.getLongExtra("caseId", 0L)

        mPresenter.selectCaseWhistleUserList(0L, userId!!, toDeptId!!)
    }


    /**
     * Dagger2 注入
     */
    override fun injectComponent() {
        DaggerCaseCenterComponent.builder()
            .activityComponent(mActivityComponent)
            .caseCenterModule(CaseCenterModule())
            .build()
            .inject(this)
        mPresenter.mView = this
    }

    /**
     * 获取单位人员列表信息回调
     */
    override fun onGetSelectCaseWhistleUserListSuccess(result: MutableList<CaseIndexUserInfoVo>) {
        val list = caseIndexDeptInfoVo?.caseIndexUserInfoVoList
        val userIdList = mutableListOf<Long>()
        // 回显已选中的人员信息
        list?.let {
            it.forEach { item ->
                userIdList.add(item.id)
            }
            result.forEach { item ->
                when (userIdList.contains(item.id)) {
                    true -> {
                        item.isChecked = true
                    }
                }
            }
        }
        indexAdapter.setDatas(result)
    }
}